package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

/**
 * 设备数据Service业务层处理
 * 
 * @author MWJ
 * @date 2025-08-23
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        LambdaQueryWrapper<DeviceData> wrapper = Wrappers.<DeviceData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime());
        Page<DeviceData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public void batchSaveDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //获取iotId，判断该设备是否存在于数据库中，来决定是否要存入设备数据
        IotMsgHeader header = iotMsgNotifyData.getHeader();
        String iotId = header.getDeviceId();
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if(device == null){
            log.error("设备不存在，iotId:{}", iotId);
            return;
        }
        IotMsgService service = iotMsgNotifyData.getBody().getServices().get(0);
        //获取上报时间并转为东八区时间
        LocalDateTime eventTime = LocalDateTime.parse(service.getEventTime(), DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")).atZone(ZoneId.of("UTC"))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //准备批量添加数据
        List<DeviceData> list = new ArrayList<>();
        //获取物模型数据
        Map<String, Object> properties = service.getProperties();
        if(ObjectUtils.isEmpty(properties)){
            return;
        }
        properties.forEach((k,v)->{
            DeviceData deviceData = new DeviceData();
            BeanUtils.copyProperties(device,deviceData);
            deviceData.setId(null);
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setFunctionId(k);
            deviceData.setDataValue(v.toString());
            deviceData.setAlarmTime(eventTime);
            list.add(deviceData);
        });
        saveBatch(list);
        //将设备最新数据覆盖缓存到Redis中，小key为设备的iotId,value为list
        redisTemplate.opsForHash().put(CacheConstants.IOT_ALL_DEVICES_DATA_NEWEST,device.getIotId(), JSONUtil.toJsonStr(list));
    }
}
